import { SessionService } from '../../services/session-service';
import { UnitService } from '../../services/unit-service';
import { FloorService } from '../../services/floor-service';
import { BuildingService } from '../../services/building-service';
import { Building, Floor, Project, Unit } from '../../shared/model/defination';
import { ProjectService } from '../../services/project-service';
import { Component, OnInit, Input } from '@angular/core';
import { MdlSnackbarService } from '@angular-mdl/core/components';

@Component({
    selector: 'app-property',
    templateUrl: './property.component.html',
    styleUrls: ['./property.component.scss'],
    providers: [ProjectService]
})
export class PropertyComponent implements OnInit {
    @Input() static = false;

    @Input() withCompany = false;

    isPosting = false;

    projects: Array<Project>;

    selectIndex: any = {
        project: -1,
        building: -1,
        floor: -1,
        unit: -1
    };

    editIndex: any = {
        project: -1,
        building: -1,
        floor: -1,
        unit: -1
    };

    selectItem: {
        project: Project;
        building: Building;
        floor: Floor;
        unit: Unit;
    } = {
        project: null,
        building: null,
        floor: null,
        unit: null
    };

    editBuilding: Building = {
        buildingAlias: '',
        buildingNumber: '',
        projectId: -1
    };

    editFloor: Floor = {
        index: '',
        alias: '',
        buildingId: -1
    };

    editUnit: Unit = {
        name: '',
        floorId: -1
    };
    constructor(
        private _projectService: ProjectService,
        private _buildingService: BuildingService,
        private _mdlSnackbarService: MdlSnackbarService,
        private _floorService: FloorService,
        private _sessionService: SessionService,
        private _unitService: UnitService
    ) {}

    get IsRoot() {
        return this._sessionService.isUserAdmin;
    }

    get CurrentProject() {
        return this.projects[this.selectIndex.project];
    }

    get CurrentBuildings() {
        return this.CurrentProject.buildings;
    }

    get CurrentFloors() {
        return this.getCurrentBuilding.floors;
    }

    set CurrentFloors(value) {
        this.getCurrentBuilding.floors = value;
    }

    get getCurrentBuilding() {
        return this.CurrentBuildings[this.selectIndex.building];
    }

    get CurrentUnits() {
        return this.CurrentFloors[this.selectIndex.floor].units;
    }

    get CurrentUnit() {
        return this.CurrentUnits[this.selectIndex.unit];
    }

    set CurrentUnits(value) {
        this.CurrentFloors[this.selectIndex.floor].units = value;
    }

    async ngOnInit() {
        if (!this.IsRoot) {
            let projectId = this._sessionService.Managable.id;
            let resp = await this._projectService.Get(projectId).toPromise();
            this.projects = [resp];
        } else {
            let resp = await this._projectService
                .getProjectsWithBuildings()
                .toPromise();
            this.projects = resp.items;
        }
    }

    clearSub(key: string) {
        if (key === 'project') {
            this.selectIndex.building = this.selectIndex.floor = this.selectIndex.unit = -1;
        }
        if (key === 'building') {
            this.selectIndex.floor = this.selectIndex.unit = -1;
        }
        if (key === 'floor') {
            this.selectIndex.unit = -1;
        }
    }

    projectClick(p, index) {
        this.selectIndex.project =
            this.selectIndex.project === index ? -1 : index;
        this.selectItem.project = this.projects[this.selectIndex.project];
        this.selectIndex.project === -1 && this.clearSub('project');
    }

    buildingClick(p, index) {
        this.selectIndex.building =
            this.selectIndex.building === index ? -1 : index;
        this.selectItem.building = this.projects[
            this.selectIndex.project
        ].buildings[this.selectIndex.building];
        this.selectIndex.building === -1 && this.clearSub('building');
    }

    floorClick(p, index) {
        this.selectIndex.floor = this.selectIndex.floor === index ? -1 : index;
        this.selectItem.floor = this.projects[
            this.selectIndex.project
        ].buildings[this.selectIndex.building].floors[index];
        this.selectIndex.floor === -1 && this.clearSub('floor');
    }

    unitClick(u, index) {
        if (!this.static) {
            return;
        }
        let locationCombine: any = {
            projectId: this.projects[this.selectIndex.project].id,
            buildingId: this.CurrentBuildings[this.selectIndex.building].id,
            floorId: this.CurrentFloors[this.selectIndex.floor].id,
            unitId: u.id
        };
        console.log(u);
    }

    async addNew(name: string) {
        try {
            if (this.isPosting) {
                return false;
            }
            this.isPosting = true;
            if (typeof this[`add${name}`] !== 'function') {
                throw new Error('not a function');
            }
            await this[`add${name}`]();
        } catch (e) {
        } finally {
            this.isPosting = false;
        }
    }

    makeBuildingEdit(i: number, event: Event) {
        this.editIndex.building = i;
        this.editBuilding = this.CurrentBuildings[i];
        event.stopPropagation();

        return false;
    }

    async addbuilding() {
        const req: any = {
            buildingNumber: this.editBuilding.buildingAlias,
            buildingAlias: this.editBuilding.buildingNumber,
            projectId: this.CurrentProject.id
        };
        if (!req.buildingNumber && !req.buildingAlias) {
            alert('楼栋号不为空');
            return false;
        }
        const ret = await this._buildingService.Create(req).toPromise();
        this.CurrentBuildings.push(ret);
        this.editBuilding.buildingAlias = '';
    }

    async confirmBuilding(event, i) {
        const req: any = {
            id: this.editBuilding.id,
            buildingNumber: this.editBuilding.buildingNumber,
            buildingAlias: this.editBuilding.buildingAlias,
            projectId: this.CurrentProject.id
        };
        if (!req.buildingNumber && !req.buildingAlias) {
            alert('楼栋号不为空');
            return false;
        }
        let ret = await this._buildingService.Update(req).toPromise();
        let building = this.CurrentBuildings.find(
            b => b.id === this.editBuilding.id
        );
        building = ret;

        this.editIndex.building = -1;
        this._mdlSnackbarService.showToast('保存成功', 2000);
        event.stopPropagation();
        return false;
    }

    async deleteBuilding($event, index) {
        const cfm = confirm('确定删除该项？');
        if (!cfm) {
            return false;
        }
        const deleteId = this.CurrentBuildings[index].id;
        this.CurrentBuildings.splice(index, 1);
        await this._buildingService.Delete(deleteId).toPromise();
        $event.stopPropagation();

        return false;
    }

    makeFloorEdit(i: number, event: Event) {
        this.editIndex.floor = i;
        this.editFloor = this.CurrentFloors[i];
        event.stopPropagation();

        return false;
    }

    async addFloor() {
        const req: any = {
            index: this.editFloor.index,
            buildingId: this.getCurrentBuilding.id
        };
        if (!req.index) {
            alert('该项不为空');
            return false;
        }
        const ret = await this._floorService.Create(req).toPromise();
        if (!this.CurrentFloors) {
            this.CurrentFloors = [];
        }
        this.CurrentFloors.push(ret);
        this.editFloor.index = '';
        this.editIndex.floor = -1;
    }

    async confirmFloor(evnet, i) {
        const req: any = {
            id: this.editFloor.id,
            index: this.editFloor.index,
            buildingId: this.editFloor.buildingId
        };
        if (!req.index) {
            alert('楼层信息不为空');
            return false;
        }
        const ret = await this._floorService.Update(req).toPromise();
        let floor = this.CurrentFloors.find(f => f.id === this.editFloor.id);
        floor = ret;

        this.editIndex.floor = -1;
        // this.editFloor.index = '';
        this._mdlSnackbarService.showToast('保存成功', 2000);

        event.stopPropagation();
        return false;
    }

    async deleteFloor($event, index) {
        const cfm = confirm('确认删除该项么?');
        if (!cfm) {
            return false;
        }
        const deleteId = this.CurrentFloors[index].id;
        this.CurrentFloors.splice(index, 1);
        await this._floorService.Delete(deleteId).toPromise();
        $event.stopPropagation();

        return false;
    }

    makeUnitEdit(i: number, event: Event) {
        this.editIndex.unit = i;
        this.editUnit = this.CurrentUnits[i];
        event.stopPropagation();

        return false;
    }
    async addUnit() {
        try {
            const req: any = {
                name: this.editUnit.name,
                floorId: this.CurrentFloors[this.selectIndex.floor].id
            };
            if (!req.name) {
                alert('该项不为空');
                return false;
            }
            const ret = await this._unitService.Create(req).toPromise();
            if (!this.CurrentUnits) {
                this.CurrentUnits = [];
            }
            this.CurrentUnits.push(ret);
            this.editUnit.name = '';
            this.editIndex.unit = -1;
        } catch (e) {
            console.error(e);
        }
    }

    async confirmUnit(evnet, i) {
        let req: any = {
            id: this.editUnit.id,
            name: this.editUnit.name,
            floorId: this.CurrentFloors[this.selectIndex.floor].id
        };
        if (!req.name) {
            alert('该项不为空');
            return false;
        }
        let ret = await this._unitService.Update(req).toPromise();
        let unit = this.CurrentUnits.find(f => f.id === this.editUnit.id);
        unit = ret;

        this.editIndex.unit = -1;
        // this.editFloor.index = '';
        this._mdlSnackbarService.showToast('保存成功', 2000);

        event.stopPropagation();
        return false;
    }

    async deleteUnit($event, index) {
        const cfm = confirm('确认删除此项？');
        if (!cfm) {
            return false;
        }
        const deleteId = this.CurrentUnits[index].id;
        this.CurrentUnits.splice(index, 1);
        await this._unitService.Delete(deleteId).toPromise();
        $event.stopPropagation();

        return false;
    }
}
